#!/usr/bin/env python
# coding: utf-8

# In[23]:


#导入库

import numpy
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import LSTM
import pandas as pd
import os
from tensorflow.keras.models import Sequential, load_model

from sklearn import preprocessing
import numpy as np

import math

from sklearn.metrics import mean_squared_error
from math import sqrt

import tensorflow as tf


# In[24]:
print("------------------------------------------------------------")

#导入数据
testdataframe = pd.read_csv(r'siyu-model/src/main/resources/csv/beforeCheck.csv',encoding='GBK',engine='python')
testdataset = testdataframe.values


# In[25]:


print(testdataframe.shape)


# In[26]:


# 将整型变为float
testdataset = testdataset.astype('float32')
# 归一化
scaler = preprocessing.MinMaxScaler(feature_range=(0, 1))
testdataset = scaler.fit_transform(testdataset)


# In[27]:


def create_dataset(dataset, look_back):
    # 这里的look_back与timestep相同
    dataX, dataY = [], []
    for i in range(len(dataset) - look_back ):
        a = dataset[i:(i + look_back)]
        dataX.append(a)
        dataY.append(dataset[i + look_back,0])
    return numpy.array(dataX), numpy.array(dataY)


# In[28]:


look_back = 9

testX, testY = create_dataset(testdataset, look_back)
testX = numpy.reshape(testX, (testX.shape[0], testX.shape[1], 2))


# In[29]:


# create the LSTM network
model = Sequential()
model.add(LSTM(8, input_shape=(None, 2)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')


# In[30]:


#获得训练后的模型参数
checkpoint_dir = r'siyu-model/src/main/resources/errorcorrection/LSTM'
model.load_weights(tf.train.latest_checkpoint(checkpoint_dir))


# In[31]:


testPredict = model.predict(testX)


# In[32]:


test_num = testX.shape[0]
print(test_num)


# In[33]:


num = 2 * look_back

testx = testX.reshape(test_num,num)[:, :2]     #改变形状
print(testx.shape)


# In[34]:


# 反归一化
testPredict = np.repeat(testPredict,2, axis=-1)#改变形状
testpred=scaler.inverse_transform(np.reshape(testPredict,(len(testPredict),2)))[:,0]


# In[35]:


#提取原始实测数据
originaltest=scaler.inverse_transform(np.reshape(testx,(len(testx),2)))[:,0]


# In[36]:


original11=scaler.inverse_transform(np.reshape(testx,(len(testx),2)))[:,0]
original22=scaler.inverse_transform(np.reshape(testx,(len(testx),2)))[:,1]

# plt.show(校正前测试集水位)
#plt.title('water level test(pre-calibration)')

#plt.plot(original11, label='real', color='b',linewidth=1)
#plt.plot(original22, color='r', label='calculation',linewidth=1)
#, linestyle=':'线形
#plt.ylabel('water level')
#plt.legend(loc='best')

#plt.savefig('校正前测试集水位（参数调用）',dpi=300)


# In[37]:


# plt.show(水位测试集)
#plt.title('water level test')

#plt.plot(originaltest, label='real', color='r',linewidth=1)
#plt.plot(testpred, color='b', label='predict',linewidth=1)
#, linestyle=':'线形
#plt.ylabel('water level')

#plt.legend(loc='best')
#plt.savefig('校正后测试集水位（参数调用）',dpi=300)


# In[38]:


#计算最大水位误差

def compute_max_difference(sequence1, sequence2):
    if len(sequence1) != len(sequence2):
        raise ValueError("The two input sequences must have the same length.")

    max_diff = 0
    max_diff_index = None

    for i in range(len(sequence1)):
        diff = abs(sequence1[i] - sequence2[i])
        if diff > max_diff:
            max_diff = diff
            max_diff_index = i

    return max_diff, max_diff_index

max_diff, max_diff_index = compute_max_difference(original11,original22)
print("校正前测试集最大差值:", max_diff)
print("最大差值出现位置:", max_diff_index)

max_diff, max_diff_index = compute_max_difference(originaltest,testpred)
print("测试集最大差值:", max_diff)
print("最大差值出现位置:", max_diff_index)


# In[39]:


from sklearn.metrics import r2_score

print('校正前测试集R^2决定系数：',r2_score(original11,original22))

print('测试集R^2决定系数：',r2_score(originaltest,testpred))


# In[40]:

print("计算完成------------------------------------------------------------")
#  将数据写入新文件
np.savetxt(r'siyu-model/src/main/resources/csv/afterCheck.csv',testpred,delimiter=',')
print("数据写入完成------------------------------------------------------------")

# In[ ]:




